<template>
  <div class="taskList">
    <listFilter
      v-if="user.id"
      ref="listFilter"
      :fields="fields"
      :default-search-fields="defaultSearchFields"
      :left-tool-tool-data="leftToolToolData"
      :search-show="searchShow"
      :key-id="keyId"
      :high-search-file="highSearchFile"
      :single-selection="singleSelection"
      @getList="getList"
    >
      <template slot="typeCode" slot-scope="{row}">
        <span>{{ typeCodeMap[row.typeCode] }}</span>
      </template>
      <template slot="showType" slot-scope="{row}">
        <span>{{ dictMap[row.showType] }}</span>
      </template>
      <template slot="isRequired" slot-scope="{row}">
        <span>{{ requireMap[row.isRequired] }}</span>
      </template>
    </listFilter>
    <taskDialog
      :visible.sync="visible"
      title="任务属性配置"
      width="60%"
      :close-check="closeCheck"
      @comfire="comfireFun"
    >
      <template slot="content">
        <addForm ref="addForm" :key="status" :params="params" :user="user" :task-show-type-option="taskShowTypeOption" />
      </template>
    </taskDialog>
  </div>
</template>

<script>
import listFilter from '@/components/listFilter'
import { getTaskAttrTenant, saveTaskAttrTenant, delTaskAttrTenant, getDictType, getTypeCodeList, getTenantId } from '@/api/portalTaskUi/taskList'
import { taskListColumnData } from '../columnData/columnData'
import taskDialog from '@/components/taskDialog'
import addForm from './components/addForm/index'
import { mapGetters } from 'vuex'
// import tranlateLabel from "../mixins/tranlateLabel";
export default {
  name: 'TaskList',
  components: {
    listFilter,
    taskDialog,
    addForm
  },
  props: {
    fields: {
      type: Array,
      default: () => taskListColumnData
    },
    searchShow: {
      type: Boolean,
      default: true
    },
    params: {
      type: Object,
      default: () => ({ attrType: 'tenant' })
    }
  },
  data() {
    return {
      defaultSearchFields: [
        { prop: 'typeCode', label: '租户名称', type: 'el-select', props: { }, placeholder: '请输入租户名称', options: [], value: '' },
        { prop: 'attrName', label: '属性名称', type: 'el-input', props: { }, placeholder: '请输入属性名称' }

      ],
      leftToolToolData: [
        { click: this.addFun, text: '新增', icon: 'el-icon-circle-plus-outline' },
        { click: this.updateFun, text: '修改', icon: 'el-icon-edit-outline' },
        { click: this.delFun, text: '删除', icon: 'el-icon-delete' }
      ],
      highSearchFile: [ // 高级搜索
        { prop: 'showType', label: '类型', type: 'el-select', props: { }, options: [], placeholder: '请选择类型' }
        // { prop: "showType", label: "类型", type: "el-select", props: { }, options: [], placeholder: "请选择类型" }
      ],
      visible: false,
      selectData: [], // 勾选的人员
      keyId: 'id',
      closeCheck: () => false,
      status: 'new',
      user: {},
      taskShowTypeOption: [],
      dictMap: {}, // 设置字典对应值
      typeCodeMap: {}, // 租户名称字典
      currentCode: '',
      singleSelection: true // 单选
    }
  },
  computed: {
    ...mapGetters(['requireMap'])
  },

  // mixins: [tranlateLabel], // 翻译的方法

  async created() {
    const getDictTypeData = await this.getDictTypeFun('task_show_type') // 设置类型字典
    const typeCodeData = await this.getTypeCodeListFun() // 获取租户名称字典
    const data = await this.getTenantIdFun() // 获取用户id
    console.log(data)
    this.user = data
    this.taskShowTypeOption = getDictTypeData
    const targetTypeOptions = typeCodeData.map(v => {
      v.value = v.id
      v.label = v.name
      return v
    })
    const targetOptions = [
      { prop: 'showType', options: getDictTypeData },
      { prop: 'typeCode', options: targetTypeOptions }
    ]
    targetOptions.forEach(s => {
      const target = this.defaultSearchFields.find(v => v.prop === s.prop) || {}
      if (target.prop === 'typeCode') {
        this.$set(target, 'disabled', data.code !== '1')
        console.log(data.id)
        this.$set(target, 'value', data.id)
      }
      this.$set(target, 'options', s.options)
    })
    this.typeOptions = targetOptions
    this.dictMap = this.setDictMap(this.taskShowTypeOption, {
      key: 'value',
      value: 'label'
    }) // 设置字典对应值
    console.log(this.dictMap)
    console.log(targetTypeOptions)
    this.typeCodeMap = this.setDictMap(targetTypeOptions, {
      key: 'id',
      value: 'name'
    }) // 租户名称字典
    console.log(this.typeCodeMap)
  },
  methods: {
    setDictMap(data, { key, value }) {
      const map = {}
      data.forEach(v => {
        if (!map[v[key]]) {
          map[v[key]] = v[value]
        }
      })
      return map
    },
    // 租户名称字典
    getTypeCodeListFun() {
      return new Promise(resolve => {
        getTypeCodeList().then(res => {
          console.log(res)
          resolve(res.data.data)
        })
      })
    },
    // 获取类型的字典
    getDictTypeFun(params) {
      // 字典名称
      return new Promise(resolve => {
        getDictType(params).then(res => {
          resolve(res.data.data)
        })
      })
    },
    // 获取用户身份
    getTenantIdFun() {
      return new Promise(resolve => {
        getTenantId().then(res => {
          resolve(res.data.data)
        })
      })
    },
    // 新增弹窗确定
    comfireFun() {
      const data = Object.assign(this.$refs.addForm.ruleForm, this.params)
      data.typeCode = this.currentCode
      console.log(data)

      const attrDictArr = ['radio', 'checkbox', 'select'] // attrDict
      const clearTarget = attrDictArr.includes(data.showType) ? 'resourceUrl' : 'attrDict'
      data[clearTarget] = ''
      saveTaskAttrTenant(data).then(res => {
        if (res.data.code === 0) {
          this.$message({
            message: '保存成功!',
            type: 'success'
          })
          this.$refs.listFilter.refreshFun()
          this.$refs.listFilter.clearSelection()
        }
      })
    },
    // 添加数据
    addFun() {
      this.visible = true
      this.status = 'new'
      this.$nextTick(() => {
        this.$refs.addForm.setFormData({})
        this.closeCheck = this.$refs.addForm.submitForm
      })
    },
    // 修改方法
    updateFun() {
      this.status = 'update'
      const selectData = this.$refs.listFilter.getCheckDataFun()
      if (selectData.length === 0) {
        this.$message({
          message: '请勾选一个元素',
          type: 'warning'
        })
        return
      }
      this.visible = true

      const data = selectData[0]
      console.log(data)
      this.$nextTick(() => {
        this.$refs.addForm.setFormData(data)
        this.closeCheck = this.$refs.addForm.submitForm
      })
    },
    // 删除
    delFun() {
      if (this.selectData.length > 0) {
        this.$confirm('你确定删除该任务属性, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const data = this.selectData.map(v => v.id)
          let type = ''
          data.forEach(v => {
            type += 'ids=' + v + '&'
          })
          const str = type.substring(0, type.length - 1)
          delTaskAttrTenant(str).then(res => {
            if (res.data.code === 0) {
              this.$refs.listFilter.refreshFun()
              this.$refs.listFilter.clearSelection()
            }
          })
        })
      } else {
        this.$message({
          message: '请选择元素',
          type: 'warning'
        })
      }
    },
    getList(index, size, query, cb) {
      const params = {
        current: index,
        size: size,
        typeCode: this.user.id
      }
      console.log(query)
      const currentParams = Object.assign(params, this.params)
      const allParams = Object.assign(currentParams, query)
      // console.log(Object.assign(currentParams, query));
      this.currentCode = allParams.typeCode
      getTaskAttrTenant(allParams).then(res => {
        const map = {
          total: res.data.data.total,
          list: res.data.data.records
        }
        cb(map)
      })
    },
    // 刷新
    refreshFun() {
      this.$refs.listFilter.refreshFun()
    }
  }
}
</script>

<style lang="less" scoped>
.taskList {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color:#fff;
}
</style>
